let db = require('../db/dbmanager');
const crypto = require('crypto');

/**
 * 管理员账号
 */
let Admin={
    checklogin:async(account,password)=>{
        return await new Promise(function (resolve, reject) {
            let sha256 = crypto.createHash('SHA256').update(password).digest('hex');
            let sql = "SELECT * FROM ADMIN WHERE username=$username and password=$password";
            let param = {$username: account, $password: sha256};

            db.sqliteDB.all(sql, param, function (err, row) {
                if (err) {
                    reject(err);
                } else {
                    resolve(row);
                }
            });
        });
    },
    insert:function(account, password){
        return new Promise(function (resolve) {
            let sql = "INSERT INTO ADMIN(username,password) VALUES ($username, $password)";
            let sha256 = crypto.createHash('SHA256').update(password).digest('hex');
            let param = {$username: account, $password: sha256};
            db.sqliteDB.run(sql, param);
            resolve();
        });
    },
    count: function(){
        return new Promise(function (resolve) {
            let sql = "SELECT COUNT(*) as c FROM ADMIN";
            db.sqliteDB.oneData(sql, (ret) => {
                resolve(ret.c)
            });
        });
    },
    changePass: function(username, old_pass, new_pass){
        // 原密码对不对
        return new Promise(function (resolve, reject) {
            Admin.checklogin(username, old_pass).then((ret) => {
                if (ret && ret.length > 0) {
                    // 更换密码
                    let sql = "UPDATE ADMIN SET password=$password WHERE username=$username";
                    let sha256 = crypto.createHash('SHA256').update(new_pass).digest('hex');
                    let param = {$username: username, $password: sha256};
                    db.sqliteDB.run(sql, param);
                    resolve();
                } else {
                    reject('原密码不正确1', username, old_pass);
                }
            }).catch((err) => {
                console.error('原密码不正确2', err)
                reject(err);
            })
        });
    },

};

module.exports = Admin;
